<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import type { Router } from 'vue-router'
import type { Ref } from 'vue'
import { showToast } from 'vant';

import { login } from '../../api/user'

import { useUserInfoStore } from '../../stores/userInfo'


const router: Router = useRouter()

const loginname: Ref<string> = ref('');
const password: Ref<string> = ref('');


const userStore = useUserInfoStore()

// console.log(userStore);


const onSubmit = () => {
    // console.log('submit', loginname.value);

    // 可以做表单验证和加密可以在此之前做

    // if (!loginname.value) {
    //     return
    // }
    // const password = md5(password.value)

    login({
        loginname: loginname.value,
        password: password.value
    }).then(res => {
        // console.log(11111, res.data.data);



        if (res.data.code == '200') {
            // 登录成功
            res.data.data.loginState = true

            // 使用 pinia 进行用户数据的全局管理
            userStore.changeUserInfoState(res.data.data)

            // 先保留用户登录信息，跳转到首页
            router.push('/')
        } else {
            // 登录失败
            showToast('温馨提示：' + res.data.message)
        }
    })
};


function goRegister() {
    router.push('/register')
}

</script>
<template>
    <div class="box">
        <header class="header">登录</header>
        <div class="content" style="padding-top: 30px">

            <van-form @submit="onSubmit">
                <van-cell-group inset>
                    <van-field v-model="loginname" name="loginname" label="用户名" placeholder="用户名"
                        :rules="[{ required: true, message: '请填写用户名' }]" />
                    <van-field v-model="password" name="password" label="密码" placeholder="密码"
                        :rules="[{ required: true, message: '请填写密码' }]" />
                </van-cell-group>
                <div style="margin: 26px;">
                    <van-button round block type="primary" color="#f66" native-type="submit">
                        登录
                    </van-button>
                </div>
                <div style="margin: 26px;">
                    <van-button @click="goRegister" round block type="success" native-type="submit">
                        注册
                    </van-button>
                </div>
            </van-form>

        </div>
    </div>
</template>